package com.zero.demo.jms.util;

import com.alibaba.fastjson.JSON;
import com.zero.demo.jms.entity.TemplateDto;
import com.zero.demo.jms.service.IExtParamComp;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zengzr
 * @desc
 * @Date 2019/5/5 14:31
 */
@Component
@Log4j2
public class BeetlUtils {
    private static CompositeResourceLoader resourceLoader;
    private static StringTemplateResourceLoader stringTemplateResourceLoader;
    private static ClasspathResourceLoader classpathResourceLoader;
    private static Configuration cfg;
    private static GroupTemplate gt;
    private static String STRING_PREFIX = "S:";
    private static String FILE_PREFIX = "F:";
    private static String path = "templates/";

    static {
        try {
            resourceLoader = new CompositeResourceLoader ();
            stringTemplateResourceLoader = new StringTemplateResourceLoader();
            classpathResourceLoader = new ClasspathResourceLoader(path,"utf-8");
            resourceLoader.addResourceLoader(new StartsWithMatcher(STRING_PREFIX),stringTemplateResourceLoader);
            resourceLoader.addResourceLoader(new StartsWithMatcher(FILE_PREFIX),classpathResourceLoader);
            cfg = Configuration.defaultConfiguration();
            gt = new GroupTemplate(resourceLoader,cfg);
        } catch (IOException e) {
            log.error("beetl模版引擎初始化异常",e.getMessage(),e);
        }
    }

    @Autowired
    StEngineConfigCacheUtils stEngineConfigCacheUtils;

    @Autowired
    DynamicComponentUtils dynamicComponentUtils;

    public String build(Long id, Map<String, Object> paramMap) throws Exception {
        if (id == null) {
            throw new Exception("传入的stEngineConfigCode不能为空!");
        }
        TemplateDto templateDto = stEngineConfigCacheUtils.getTemplateDtoById(id+"");
        return build( templateDto, paramMap);
    }


    public String build(TemplateDto templateDto, Map<String, Object> paramMap) throws Exception {
        String template = templateDto.getTempContent();
        Long extCompId = templateDto.getCompId();
        String extParamJson = templateDto.getExtParams();
        Map<String, Object> extParam = StringUtils.isNotEmpty(extParamJson) ? (Map<String, Object>) JSON.parse(extParamJson) : new HashMap<>();
        if (paramMap != null) {
            extParam.putAll(paramMap);
        }
        if (extCompId != null && extCompId > 0) {
            Object extParamComp = dynamicComponentUtils.getBean(extCompId,Object.class);
            if(extParamComp instanceof IExtParamComp){
                ((IExtParamComp)extParamComp).buildExtParam(extParam);
            }else {
                throw  new RuntimeException("类文件内容异常，编译后的类需实现IExtParamComp或IExtParamComp4DB接口!");
            }
        }
        String renderString = buildString(extParam, template);
        return renderString;
    }


    public String buildString( Map<String, Object> extParam, String template) {
        Template st = gt.getTemplate(STRING_PREFIX + template);
        st.binding("result", extParam);
        return st.render();
    }

    public String buildFile(Map<String, Object> extParam, String templatePath) {
        Template st = gt.getTemplate(FILE_PREFIX + templatePath);
        st.binding("result", extParam);
        return st.render();
    }
}
